var app = new Vue({
	el: '#app',
	data: {
		userMsg: {
			isLogin: false,
			id: null,
			account: null,
			name: null,
			headimg: null
		},
		newname: '',
		haveChangeImg: false,
		oldpassword: '',
		newpassword: ''
	},
	watch: {
	},
	methods: {
		changePassword: function(){
			var self = this;
			var id = self.userMsg.id;
			var oldpassword = self.oldpassword;
			var newpassword = self.newpassword;
			var data = {
				"id": id,
				"oldpassword": oldpassword,
				"newpassword": newpassword
			}
			$.post("/api/changePassword", data, function(data,status){
				if (data.success == "ok") {
					$("#passwordModal").modal("hide");
					swal("修改成功","","success");
				} else {
					swal("修改失败",data.msg, "error");
				}
			})
		},
		logout: function(){
			var self = this;
			swal({ 
				title: "确定退出吗？", 
				type: "warning",
				showCancelButton: true, 
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定", 
  				cancelButtonText: "取消"
			},function(){
				$.post("/api/logout",{},function(data,status){
					if (data.success = "ok") {
						self.getLoginStatus();
					}
				});
			});

		},
		getLoginStatus: function(){
			var self = this;
			$.get('/api/isLogin',function(data,status){
				if (data.success == "ok") {
					self.userMsg.isLogin = true;
					self.userMsg.name = data.result.name;
					self.userMsg.id = data.result.id;
					self.userMsg.account = data.result.account;
					self.userMsg.headimg = data.result.headimg;
				} else {
					self.userMsg.isLogin = false;
				}
			})
		},
		getQueryString: function(name) { 
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
			var r = window.location.search.substr(1).match(reg); 
			if (r != null) return unescape(r[2]); return null; 
		},
		uploadHeadimg: function(){
			var self = this;
			var formData = new FormData($("#uploadForm")[0]);
			$.ajax({    
				url: '/api/upload' ,  /*这是处理文件上传的servlet*/  
				type: 'POST',    
				data: formData,    
				async: false,    
				cache: false,    
				contentType: false,    
				processData: false,    
				success: function (result) {
					if (result.success == true) {
						self.userMsg.headimg = result.file_path;
						self.haveChangeImg = true;
					}
				},    
				error: function (result) {
					swal("上传失败","网络原因","error")
				}    
			});  
		},
		save: function(){
			var self = this;
			var imgurl = self.userMsg.headimg;
			var name = self.newname;
			var data = {"id":self.userMsg.id}
			if (name == undefined && name == "") {
				swal("昵称不能为空哦","","waring");
				return;
			} 

			data.name = name;

			if (self.haveChangeImg) {
				data.headimg = self.userMsg.headimg;
			}

			$.post('/api/setUser', data, function(data,status){
				if (data.success == "ok") {
					swal("修改成功","","success");
					self.getLoginStatus();
				} else {
					swal("修改失败",data.msg,"error");
				}
			})

		}

	},
	mounted: function(){
		var self = this;
		this.getLoginStatus();
		$("#uploadForm").change(function(){
			self.uploadHeadimg();
		})
	}
})
